package cn.gok.demo2.service;

import cn.gok.demo2.domain.User;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @ClassName UserService
 * @Description TODO
 * @Author HP
 * @Date 15:21 2022/8/16
 * @Version 1.0
 **/
@Service
@Slf4j
public class UserService {

    private final static Map<String, User> USER_MAP = Maps.newConcurrentMap();

    static {
        USER_MAP.put("A", new User("A", "userA"));
        USER_MAP.put("B", new User("B", "userB"));
        USER_MAP.put("C", new User("C", "userC"));
    }

    @Cacheable(value = "user",key = "#id")
    public User get(String id) {
        User user = USER_MAP.get(id);
        log.info("查询用户:{}--{}", id, user);
        return user;
    }

    @CachePut(value = "user",key = "#user.id")
    public User save(User user) {
        USER_MAP.put(user.getId(), user);
        log.info("保存用户:{}--{}", user.getId(), user);
        return user;
    }

    @CacheEvict(value = "user",key = "#id")
    public void delete(String id) {
        User user = USER_MAP.remove(id);
        log.info("删除用户:{}--{}", user.getId(), user);
    }

}
